<template>
	<view class="edit-page">
		<van-nav-bar :title="navTitle" left-text="返回" left-arrow @click-left="Back" />
		<van-address-edit :area-list="areaList" :address-info="address_default" :show-delete=" id? true:false "
			sbow-area show-detail show-set-default :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave"
			@delete="onDelete(id)" @change-default="onChangeDefault" />

	</view>
</template>

<script setup>
	// 导入的城市信息
	import {
		areaList
	} from '@vant/area-data'

	console.log(areaList)

	// 导入封装的请求
	import $api from '../../request/index.js'

	// 导入页面的生命周期
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'

	import {
		ref
	} from 'vue'
	import {
		showSuccessToast
	} from 'vant'

	/*
		name:
		tel:
		province:
		city:
		county:
		addressDetail:
		areaCode:
		isDefault:
		id: 地址唯一标识
		uid: 副键 用户的id
	*/


	let navTitle = ref('修改/新增地址')
	let address_default = ref({})
	let id = ref('')

	// 页面初始化
	onLoad(payload => {
		navTitle.value = payload.id ? '修改地址' : '新增地址'
		id.value = payload.id
		// 根据id 获得初始地址
		if (payload.id) {
			$api.get('/moto/address/selectAddressById/' + payload.id).then(res => {
				console.log('得到的', res.data)
				res.data.areaCode = res.data.areaCode.toString();
				res.data.isDefault = res.data.isDefault ? true : false
				console.log('处理后的', res.data)
				address_default.value = res.data
			})
		}
	})


	// 保存地址
	const onSave = address => {
		try {
			// 拿到form 表单的数据
			console.log(address)
			address.isDefault = address.isDefault ? 1 : 0

			if (!id.value) {
				// 添加地址
				console.log('添加地址')
				$api.post('/moto/address/addAddress', address).then(res => {
					if (res.code) {
						showSuccessToast('添加成功')
						uni.navigateBack()
					}
				})
			} else {
				// 修改地址
				address.id = id.value
				$api.post('/moto/address/updateAddressById', address).then(res => {
					if (res.code) {
						showSuccessToast('修改成功')
						uni.navigateBack()
					}
				})
			}
		} catch (error) {
			console.log(error)
		}
	}


	// 删除地址
	const onDelete = e => {
		console.log(e)
		$api.Delete('/moto/address/deleteAddress/' + e).then(res => {
			if (res.code) {
				showSuccessToast('删除成功')
				uni.navigateBack()
			}
		})
	}

	// 设置默认地址
	const onChangeDefault = (val) => {
		console.log(val)
	}

	// 返回
	const Back = () => uni.navigateBack()
</script>

<style>

</style>